#include "componentdetailpage.h"
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QScrollArea>
#include <QDebug> // For placeholder messages
#include <QSpacerItem>
#include <QStringList>
#include <QPixmap>

ComponentDetailPage::ComponentDetailPage(QWidget *parent) : QWidget(parent) {
    setupUserInterface();
    connect(internalBackButton, &QPushButton::clicked, this, &ComponentDetailPage::onInternalBackButtonClicked);
}

ComponentDetailPage::~ComponentDetailPage() {
    // 析构函数
}

void ComponentDetailPage::setupUserInterface() {
    mainLayout = new QVBoxLayout(this); // Main layout for the ComponentDetailPage widget itself
    setLayout(mainLayout); // Apply mainLayout to this widget

    scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame); // Optional: remove frame from scroll area

    scrollAreaWidgetContents = new QWidget(); // This widget will contain the actual content and be scrollable
    scrollArea->setWidget(scrollAreaWidgetContents);

    // 滚动区域内部内容的布局
    rightInfoPanelLayout = new QVBoxLayout(scrollAreaWidgetContents); 
    // scrollAreaWidgetContents->setLayout(rightInfoPanelLayout); // 为可滚动内容控件设置布局

    // 整体页面结构：左侧图片，右侧可滚动信息
    topContentLayout = new QHBoxLayout(); 

    // 图片（左侧部分）
    imageLabel = new QLabel("图片占位符");
    imageLabel->setMinimumSize(250, 250); 
    imageLabel->setMaximumSize(350, 350);
    imageLabel->setAlignment(Qt::AlignCenter);
    imageLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
    imageLabel->setObjectName("componentImageLabel");
    topContentLayout->addWidget(imageLabel, 1); // Stretch factor 1 for image side

    // 将 scrollArea（包含 rightInfoPanelLayout）添加到 topContentLayout 的右侧部分
    topContentLayout->addWidget(scrollArea, 2); // Stretch factor 2 for info side

    // --- 填充 rightInfoPanelLayout（可滚动区域的内容） ---
    // 基本信息部分
    basicInfoTitleLabel = new QLabel("<b>基本信息</b>");
    basicInfoTitleLabel->setObjectName("detailSectionTitleLabel");
    modelValueLabel = new QLabel();
    brandValueLabel = new QLabel();
    categoryValueLabel = new QLabel();
    packageValueLabel = new QLabel();
    supplierValueLabel = new QLabel();
    stockValueLabel = new QLabel();
    
    QGridLayout* basicInfoLayoutGrid = new QGridLayout();
    basicInfoLayoutGrid->addWidget(new QLabel("型号:"), 0, 0, Qt::AlignTop); basicInfoLayoutGrid->addWidget(modelValueLabel, 0, 1);
    basicInfoLayoutGrid->addWidget(new QLabel("品牌:"), 1, 0, Qt::AlignTop); basicInfoLayoutGrid->addWidget(brandValueLabel, 1, 1);
    basicInfoLayoutGrid->addWidget(new QLabel("分类:"), 2, 0, Qt::AlignTop); basicInfoLayoutGrid->addWidget(categoryValueLabel, 2, 1);
    basicInfoLayoutGrid->addWidget(new QLabel("封装:"), 3, 0, Qt::AlignTop); basicInfoLayoutGrid->addWidget(packageValueLabel, 3, 1);
    basicInfoLayoutGrid->addWidget(new QLabel("供应商:"), 4, 0, Qt::AlignTop); basicInfoLayoutGrid->addWidget(supplierValueLabel, 4, 1);
    basicInfoLayoutGrid->addWidget(new QLabel("库存:"), 5, 0, Qt::AlignTop); basicInfoLayoutGrid->addWidget(stockValueLabel, 5, 1);
    
    rightInfoPanelLayout->addWidget(basicInfoTitleLabel);
    rightInfoPanelLayout->addLayout(basicInfoLayoutGrid);
    rightInfoPanelLayout->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Fixed));

    // 规格参数部分
    specsTitleLabel = new QLabel("<b>规格参数</b>");
    specsTitleLabel->setObjectName("detailSectionTitleLabel");
    specsContainerWidget = new QWidget(); // Container for the specsLayout
    specsLayout = new QGridLayout(specsContainerWidget); 
    // specsContainerWidget->setLayout(specsLayout); // 将布局应用到容器
    rightInfoPanelLayout->addWidget(specsTitleLabel);
    rightInfoPanelLayout->addWidget(specsContainerWidget);
    rightInfoPanelLayout->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Fixed));

    // 封装信息部分
    packageInfoTitleLabel = new QLabel("<b>封装信息</b>");
    packageInfoTitleLabel->setObjectName("detailSectionTitleLabel");
    packageInfoContainerWidget = new QWidget(); // Container for the packageInfoLayout
    packageInfoLayout = new QGridLayout(packageInfoContainerWidget);
    // packageInfoContainerWidget->setLayout(packageInfoLayout); // 将布局应用到容器
    rightInfoPanelLayout->addWidget(packageInfoTitleLabel);
    rightInfoPanelLayout->addWidget(packageInfoContainerWidget);
    
    rightInfoPanelLayout->addStretch(1); // Pushes content up if not enough to fill scroll area

    // 将 topContentLayout（图片 | 可滚动信息）添加到页面的 mainLayout
    mainLayout->addLayout(topContentLayout);

    // 页面底部的返回按钮
    internalBackButton = new QPushButton("返回");
    internalBackButton->setObjectName("detailBackButton");
    QHBoxLayout* bottomButtonLayout = new QHBoxLayout();
    bottomButtonLayout->addStretch();
    bottomButtonLayout->addWidget(internalBackButton);
    // bottomButtonLayout->addStretch(); // 居中按钮或右对齐
    mainLayout->addLayout(bottomButtonLayout);
    mainLayout->setStretchFactor(topContentLayout, 1); // Give more space to content

    clearPageContent(); // Initialize with empty/default values
}

void ComponentDetailPage::loadComponentData(const Component* componentData, const QString& supplierName) {
    clearPageContent();
    if (!componentData) {
        qWarning() << "ComponentDetailPage::loadComponentData called with nullptr";
        // 可选地，在页面本身显示消息
        modelValueLabel->setText("错误：无组件数据");
        return;
    }

    modelValueLabel->setText(QString::fromUtf8(componentData->model));
    brandValueLabel->setText("N/A"); // Placeholder - to be implemented if data available
    categoryValueLabel->setText("N/A"); // Placeholder
    packageValueLabel->setText(QString::fromUtf8(componentData->package));
    supplierValueLabel->setText(supplierName); // Use the name passed from MainWindow
    stockValueLabel->setText(QString::number(componentData->quantity));

    // 图片加载
    if (componentData->image_path[0] != '\0') {
        QPixmap pixmap(QString::fromUtf8(componentData->image_path));
        if (!pixmap.isNull()) {
            imageLabel->setPixmap(pixmap.scaled(imageLabel->width(), imageLabel->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
        } else {
            imageLabel->setText(QString("无法加载图片:\n%1").arg(QString::fromUtf8(componentData->image_path)));
        }
    } else {
        imageLabel->setText("无图片");
    }

    // 从描述中解析并显示规格
    QString desc = QString::fromUtf8(componentData->description);
    QStringList specsList = desc.split(';', Qt::SkipEmptyParts);
    int specRow = 0;
    if (!specsList.isEmpty()) {
        for (const QString& specPairStr : specsList) {
            QStringList pair = specPairStr.split(':', Qt::SkipEmptyParts); // Use SkipEmptyParts here too
            if (pair.size() == 2) {
                QLabel* specNameLabel = new QLabel(pair[0].trimmed() + ":");
                QLabel* specValueLabel = new QLabel(pair[1].trimmed());
                specValueLabel->setWordWrap(true);
                specsLayout->addWidget(specNameLabel, specRow, 0, Qt::AlignTop);
                specsLayout->addWidget(specValueLabel, specRow, 1);
                specRow++;
            } else if (pair.size() == 1 && !pair[0].trimmed().isEmpty()) { // Handle case of description not in pair format
                 if (specRow == 0) { // Only add as general description if it's the first item and not a pair
                    QLabel* descLabel = new QLabel("描述:");
                    QLabel* descValueLabel = new QLabel(pair[0].trimmed());
                    descValueLabel->setWordWrap(true);
                    specsLayout->addWidget(descLabel, specRow, 0, Qt::AlignTop);
                    specsLayout->addWidget(descValueLabel, specRow, 1);
                    specRow++;
                 }
            }
        }
    }
    if (specRow == 0 && !desc.isEmpty()) { // If description was not empty but not parsed as specs
        QLabel* descLabel = new QLabel("描述:");
        QLabel* descValueLabel = new QLabel(desc);
        descValueLabel->setWordWrap(true);
        specsLayout->addWidget(descLabel, specRow, 0, Qt::AlignTop);
        specsLayout->addWidget(descValueLabel, specRow, 1);
    }


    // 封装信息的占位符（可以类似地扩展）
    packageInfoLayout->addWidget(new QLabel("类型:"), 0, 0, Qt::AlignTop);
    packageInfoLayout->addWidget(new QLabel(QString::fromUtf8(componentData->package)), 0, 1);
}

void ComponentDetailPage::clearPageContent() {
    modelValueLabel->setText("-");
    brandValueLabel->setText("-");
    categoryValueLabel->setText("-");
    packageValueLabel->setText("-");
    supplierValueLabel->setText("-");
    stockValueLabel->setText("-");
    imageLabel->setText("图片占位符");
    imageLabel->setPixmap(QPixmap()); // Clear any existing pixmap

    QLayoutItem* item;
    while ((item = specsLayout->takeAt(0)) != nullptr) {
        if (item->widget()) {
            delete item->widget();
        }
        delete item;
    }
    while ((item = packageInfoLayout->takeAt(0)) != nullptr) {
        if (item->widget()) {
            delete item->widget();
        }
        delete item;
    }
}

void ComponentDetailPage::onInternalBackButtonClicked() {
    emit backToMainRequested();
}